package com.crowdfunding.backend.repo;

import com.crowdfunding.backend.dto.UserDto;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;

@Repository
public class UserRepository {

    private final JdbcTemplate jdbc;

    public UserRepository(JdbcTemplate jdbc) { this.jdbc = jdbc; }

    private final RowMapper<UserDto> mapper = new RowMapper<UserDto>() {
        @Override
        public UserDto mapRow(ResultSet rs, int rowNum) throws SQLException {
            UserDto u = new UserDto();
            u.id = rs.getInt("id");
            u.username = rs.getString("username");
            u.email = rs.getString("email");
            u.eoaAddress = rs.getString("eoa_address");
            u.createdAt = rs.getLong("created_at");
            return u;
        }
    };

    public Optional<UserDto> findByEmail(String email) {
        java.util.List<UserDto> list = jdbc.query("SELECT * FROM users WHERE email = ?", mapper, email);
        return list.stream().findFirst();
    }

    public Optional<String> getPasswordHashByEmail(String email) {
        java.util.List<String> list = jdbc.queryForList("SELECT password_hash FROM users WHERE email = ?", String.class, email);
        return list.stream().findFirst();
    }

    public Optional<UserDto> findByUsername(String username) {
        java.util.List<UserDto> list = jdbc.query("SELECT * FROM users WHERE username = ?", mapper, username);
        return list.stream().findFirst();
    }

    public Optional<UserDto> findById(int id) {
        java.util.List<UserDto> list = jdbc.query("SELECT * FROM users WHERE id = ?", mapper, id);
        return list.stream().findFirst();
    }

    public int create(String username, String email, String passwordHash, String eoaAddress, long createdAt) {
        jdbc.update("INSERT INTO users(username,email,password_hash,eoa_address,created_at) VALUES(?,?,?,?,?)",
                username, email, passwordHash, eoaAddress, createdAt);
        Integer id = jdbc.queryForObject("SELECT last_insert_rowid()", Integer.class);
        return id == null ? -1 : id;
    }

    public void updateEoaById(int id, String eoaAddress) {
        jdbc.update("UPDATE users SET eoa_address = ? WHERE id = ?", eoaAddress, id);
    }
}
